package service.demo;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;


public class JClient {
    TTransport transport;

    public <T> T build(Class<T> clazz) throws TTransportException {
        TProtocol protocol = getProtocal();

        Object client = null;
        try {
            Constructor constructor = clazz.getDeclaredConstructor(new Class[]{TProtocol.class});
            constructor.setAccessible(true);
            client = constructor.newInstance(new Object[]{protocol});
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) client;
    }

    public void close() {
        transport.close();
    }

    private TProtocol getProtocal() throws TTransportException {
        transport = new TSocket("localhost", 9080);
        transport.open();
        return new TBinaryProtocol(transport);
    }

    public static void main(String[] args) throws TException {
        JClient jclient = new JClient();
        Hello.Client client = jclient.build(Hello.Client.class);
        for (int i = 0; i < 100; i++) {
            System.out.println(client.helloBoolean(true));
        }
        jclient.close();
    }

}
